/**
 * 全局类，用于存储常用方法和
 * 全局变量
 */
;
var cmedit = {};
cmedit.global =
    (function ($, window, document) {
        return {
        	/** 版本号 */
        	version: "V2.0.8_Build20200720",
        	updatetime:  "2020-07-20",
        	
            /** 应用名，如 CloudFileBase */
            appName: "dywebpageweb",
            /** 应用根路径,为空则表示是单体应用，默认获取contextPath路径,不为空则是配置路径*/
            appPath: "",
            
            //【非零配置下使用这个，零配置时注释掉】
            //portalPath: "http://dayang.fast.com:8087/dyportalserver/", //portal服务地址
            //【零配置方案下使用这个，非零配置时注释掉】
            portalPath: window.top.location.href.substring(0,window.location.href.indexOf("dywebpageweb")) + "dyportalserver/",
            
            cmsPath: "", //网页后台服务路径
            system_cmedit_id: "PID_Fast_cmedit",//稿件系统标识
            system_cmedit_cms_id: "PID_Fast_cmedit_cms",
            cmedit_server_code: "PUB_CMEDIT_CMS_SERVER", //后台服务路径OODE
            cmedit_server_name: "dywebpageserver", //后台服务名
            portal_web: "PUB_PORTAL_WEB", //portal前端地址
            userInfo: "userInfo",
            userInfoDetail: "userInfoDetail",
            superTimeout: 18000000,   //登录过期超时时间 3个小时
            myTimeOut:'',//删除用户信息的定时器ID
            userInfoDetail: "userInfoDetail",
            columnInfo: "columnInfo",
            allColumnInfo: "allColumnInfo",
            privilegeInfo: "privilegeInfo",
            privilegeIds: "privilegeIds",
            userColumnIds : "userColumnIds",
            allColumnIds : "allColumnIds",
            bigColumnId : "bigColumnId",
            CFBFlag : "CFBFlag",
            CREFlag : "CREFlag",
            lanYunFlag : "lanYunFlag",
            daGuanFlag : "daGuanFlag",
            rabbitmqFlag : "rabbitmqFlag",
            CREFuncFlag : "CREFuncFlag",
            lvFuncFlag : "lvFuncFlag",
            rongZhiLianFlag : "rongZhiLianFlag",
            rongYunRRFlag : "rongYunRRFlag",
            rongYunTAFlag : "rongYunTAFlag",
            rongYunMCFlag : "rongYunMCFlag",
            hogeFlag : "hogeFlag",
            saveAutoFlag : "saveAutoFlag",
            saveInterval : "saveInterval",
            creImportTaskFlag : "creImportTaskFlag",
            GifFlag : "GifFlag",
            SubtitleFlag : "SubtitleFlag",
            cmeditTypes : "cmeditTypes",
            cmeditList : "cmeditList",
            loadTimeout : 1000,
            CFBExternalUrl : "CFBExternalUrl",
            privilegeWritescripts : "PID_CMEDIT_WRITESCRIPTS",//撰写全媒体稿件
            privilegeAuditscripts : "PID_CMEDIT_AUDITSCRIPTS",//审核全媒体稿件
            privilegeEditallscripts : "PID_CMEDIT_EDITALLSCRIPTS",//修改全部全媒体稿件
            privilegeDelallscripts : "PID_CMEDIT_DELALLSCRIPTS",//删除全部全媒体稿件
            privilegeConfigure : "PID_CMEDIT_CONFIGURE",//全媒体稿件系统管理
            privilegeExportword : "PID_CMEDIT_EXPORTWORD",//下载word
            privilegeFinalcensor : "PID_CMEDIT_FINALCENSOR",//终审浏览
            privilegeDistribute : "PID_CMEDIT_DISTRIBUTE",//签发权限
            privilegeFinished : "PID_CMEDIT_FINISHED",//成品稿库权限
            privilegeDistributeRevoke : "PID_CMEDIT_FINISHED_REVOKE",//成品稿库签发撤回权限
            privilegeEditAuditscripts : "PID_CMEDIT_EDITAUDITSCRIPTS",//修改审核中权限
            privilegeEditFinishscripts : "PID_CMEDIT_EDITFINISHSCRIPTS",//修改成品稿库权限
            privilegeEditColumnscripts : "PID_CMEDIT_EDITCOLUMNSCRIPTS",//修改本栏目权限
            privilegeDelFinishscripts : "PID_CMEDIT_DELFINISHSCRIPTS",//删除成品稿件权限
            privilegeReAuditscripts : "PID_CMEDIT_REAUDIT",//反审核权限，对自己审核已通过的稿件发起反审
            cmsTargetTypeCode : "EDIT_HOGE_TARGET_TYPE",
            cre_cre: "PUB_CRECRE", //CRE API地址
            tipwindowWidth: 900,       //预览窗口宽度
            tipwindowHeight: 620,       //预览窗口高度
            isPublish:true,//true:发布模式  false:开发模式（不引头部）
            loaderHtml:'<div class="manuLoader"><div id="preloader_1"><span></span><span></span><span></span><span></span></div></div>',
            /* 动态配置相关 START */
            cmeditList : "cmsFiled_list", //列表页字段
            cmeditSendTask : "cmsFiled_sendtask", //成品稿库页字段
            cmeditTask : "cmsFiled_task", //审核任务页字段
            cmeditSend : "cmsFiled_send", //签发监控页字段
            cmeditDownload : "cmsFiled_download", //下载监控字段
            cmeditRecycle : "cmsFiled_recycle", //回收站页字段
            cmeditFinal : "cmsFiled_final", //终审浏览页字段
            cmeditEdit : "cmsFiled_edit", //编辑页字段
            sobey_cfbserver: "TENANT_SOBEY_CFBSERVER",
            distributeFlag: "TENANT_EDIT_DISTRIBUTE_FLAG",//分发调用方式
            EDIT_CRE_CBBV_FLAG: "EDIT_CRE_CBBV_FLAG", //资源库开关
            PUB_PORTAL_CODE:"dyportalweb/",
            /* 动态配置相关 END */
            init: function () {
                /*$.ajax({
                  url: window.location.protocol + '//' + window.location.host + "/dyportalweb/configutil.js",
                  type: 'GET',
                  async: false,
                  dataType: "script",
                  success: function(){
                    debugger
                    cmedit.global.portalPath = dyportalGlobal.configs.dyportalserverPath;
                  }
                });*/  
               this.initAppPath();
               this.initServerPath();
//               this.sessionExpirationAjax();
            },
            initAppPath: function() {
                var pathName = document.location.pathname;
                if (!cmedit.global.isNotEmpty(this.appPath)) {
                    var appPath = window.sessionStorage.getItem("cms_appPath");
                    if (cmedit.global.isNotEmpty(appPath)) {
                        this.appPath = appPath;
                    } else {
                        this.appPath = cmedit.global.getContextPath(pathName) + "/";
                        window.sessionStorage.setItem("cms_appPath",this.appPath);
                    }
                }
            },
            initServerPath: function() {
                if (!cmedit.global.isNotEmpty(this.cmsPath)) {
                	var cmsPath = window.sessionStorage.getItem("cms_serverPath");
                	if (cmedit.global.isNotEmpty(cmsPath)) {
                        this.cmsPath = cmsPath;
                    } else {
                    	if(window.location.href.indexOf("gateway") > -1){
                    		console.log("当前为网关部署方式");
                    		this.cmsPath = window.location.protocol + '//' + window.location.host + "/gateway/dywebpageserver/";
                    	}else{
                    		this.cmsPath = this.getParamterByCode(cmedit.global.cmedit_server_code,"");
                    	}
                        window.sessionStorage.setItem("cms_serverPath",this.cmsPath);
                    }
                }
                
            },
            //设置AJAX的全局默认选项  
            sessionExpirationAjax: function(){                
                $.ajaxSetup({  
                    complete: function(XHR,status) {
                    	cmedit.global.redirectHandle();
                    },
                });  
            },
            redirectHandle:function(){
                $.ajax({
                    type: "get",
                    async: true,
                    url: window.location.protocol + '//' + window.location.host+"/gateway/checkValidator",
                    dataType: "json",
                    contentType: "application/json;charset=UTF-8",
                    headers: {
                    "tenantId": window.localStorage.getItem("tenantId"),
                    "token": window.localStorage.getItem("token"),
                    },
                    complete: function(XHR){
                        var enable = XHR.responseJSON;
                        console.log("enable = " + enable);
                        if(enable !=true){
                        	cmedit.global.alertBox("会话过期！", true);
                        }  
                    }
                });
            },
            /**
             * 会话过期
             */
            alertBox: function(content, switchToLogin) {
                var isAlert = true;
                if (window.top.$('#headerPlugin_mask').length > 0) {
                    isAlert = false;
                }
                if (isAlert) {
                    window.top.$('body').append('<div id="headerPlugin_mask" style="position:fixed;top:0;width:100%;height:100%;z-index:100000;" ></div>');
                    var alertBox = '<div id="manuscript_alert"' +
                        'style="position:absolute;top:20%;left:50%;transform:translateX(-50%);width:300px;height:150px;z-index:999999;border:1px solid #e5e5e5;box-shadow:4px 4px 2px #666;border-radius:3px!important;padding:30px;background:#fff;">' +
                        '<div style="width:100%;height:60%;text-align:center;font-size:16px;padding:20px 0;">' + content + '</div>' +
                        '<div style="width:100%;text-align:center;">' +
                        '<span style="width:70px;height:34px;line-height:34px;display:inline-block;cursor:pointer;text-align:center;border:1px solid #3598dc;background:#3598dc;border-radius:3px!important;color:#fff;">确定</span>' +
                        '</div>' +
                        '</div>'
                    window.top.$('body').append(alertBox);
                    $('#manuscript_alert span').on('click', function() {
                        window.top.$('#headerPlugin_mask').remove();
                        window.top.$('#manuscript_alert').remove();
                        if (switchToLogin) {
                        	cmedit.global.switchToLogin();
                        }
                    });
                }
            },
            /**
             * 跳转到登录页
             */
            switchToLogin: function() {
            	window.sessionStorage.clear();
            	window.localStorage.clear();
                var gatewayAddress = window.top.location.href.split("gateway")[0] + "gateway/";
                var logoutAddress = gatewayAddress + "casLogout?service=";
                var service = gatewayAddress + "dyportalserver/loginBycas";
                window.location.href = logoutAddress + service; //返回cas登录页
            },
            /**
             * 根据参数code从配置服务获取参数值
             * 
             * @param parameterCode 参数code 必填
             * @param appGuid 应用ID(查询应用参数时传递) 非必填
             * @returns
             */
            getParamterByCode: function (parameterCode,appGuid) {
                var parameterValue = "";
                var userInfoItem = window.localStorage.getItem("login_casData");
                var userInfo = null;
                var userId = "";
                var tenantId = "";
                var token = "";
                var userName = "";
                if (userInfoItem != undefined && userInfoItem != null && userInfoItem != "" && userInfoItem != "undefined" && userInfoItem != "null") {
                    userInfo = JSON.parse(userInfoItem);
                    userId = userInfo.userId;
                    tenantId = userInfo.tenantId;
                    userName = userInfo.userName;
                    token = userInfo.token;
                } 
                $.ajax({
                    type: 'POST',
                    async: false,
    				url: cmedit.global.portalPath + "ParameterController/getParameter",
    				beforeSend: function (XHR) {
                        XHR.setRequestHeader("userId", userId);
                        XHR.setRequestHeader("tenantId", tenantId);
                        XHR.setRequestHeader("token", token);
                        XHR.setRequestHeader("userName",encodeURIComponent(userName));
                    },
    				data: {
    					appGuid : appGuid,
    					parameterCode : parameterCode
    				},
                    success: function (data) {
                        if (data.status == true || data.status == "true") {
                        	parameterValue = data.data[0].parameterValue;
                        } else {
                            cmedit.global.alertMsgNoCancel(data.msg);
                        }
                    }
                });
                return parameterValue;
            },
            getPortalWeb : function(){
            	if(window.location.href.indexOf("gateway") > -1){
            		console.log("当前为网关部署方式");
            		return window.location.protocol + '//' + window.location.host + "/gateway/dyportalweb/";
            	}else{
            		this.wechatPath = this.getParamterByCode("PUB_GATEWAY_OUTERNET_SERVER",window.localStorage.getItem("tenantId")) + "dyportalweb/";
            	}
            },
            /**
             * 根据应用code从应用信息
             * 
             * @param appCode 应用代码
             * @returns
             */
            getAppByCode: function (appCode,tenantId) {
                var app = "";
                $.ajax({
                    type: 'POST',
                    async: false,
    				url: cmedit.global.portalPath + "AppController/getAppList",
    				data: {
    					appCode : appCode
    				},
    				beforeSend: function (XHR) {
            			XHR.setRequestHeader("tenantId", tenantId);
                	},
                    success: function (data) {
                        if (data.status == true || data.status == "true") {
                        	app = data.data[0];
                        } else {
//                            cmedit.global.alertMsgNoCancel(data.msg);
                        }
                    }
                });
                return app;
            },
            /**
             * 根据稿件类型，获取稿件的前端地址
             * @param maintype 稿件类型
             * @returns
             */
            getAppPathByType : function(maintype){
            	var app;
            	if(maintype == '0'){
            		app = cmedit.global.getAppByCode("PID_Fast_cmedit_cms");
            	}
            	if(maintype == '1'){
            		app = cmedit.global.getAppByCode("PID_Fast_cmedit_wechat");
            	}
            	if(maintype == '2'){
            		app = cmedit.global.getAppByCode("PID_Fast_cmedit_weibo");
            	}
            	if(maintype == '3'){
            		app = cmedit.global.getAppByCode("PID_Fast_cmedit_tv");
            	}
            	if(maintype == '4'){
            		app = cmedit.global.getAppByCode("PID_Fast_cmedit_release");
            	}
            	return app.appUrl;
            },
            /**
             * 表单序列化
             */
            serializeArray : function(form){
            	var o = {};
                x=$(form).serializeArray();
                $.each(x, function(i, field){
                    if (o[this['name']]) {
                        o[this['name']] = o[this['name']] + "," + this['value'];
                    } else {
                        o[this['name']] = this['value'];
                    }
                });
                return o;
            },
            isNotEmpty: function(obj){
                var isflag = false;
                if(obj!=null&&obj!=''&&obj!=undefined&&obj!='undefined'){
                    isflag = true;
                }
                return isflag;
            },
            getContextPath: function (pathName) {
                var index = pathName.substr(1).indexOf("/");
                var result = pathName.substr(0, index + 1);
                return result;
            },
            /**
             * 无取消按钮的提示框
             * @param content  提示内容
             */
            alertMsgNoCancel: function (content) {
                art.dialog({
                    content: content,
                    height: 60,
                    width: 300,
                    lock: true,
                    focus: true,
                    zIndex: 99999999
                }, function () {
                });
            },
            /**
    		 * 动态加载js文件
    		 */
    		loadScript : function(url) {
    			var script = document.createElement("script");
    			script.type = "text/javascript";
    			script.src = url;
    			document.body.appendChild(script);
    		},
    		/**
    		 * 动态加载css文件
    		 */
    		loadStyles : function(url) {
    			var link = document.createElement("link");
    			link.type = "text/css";
    			link.rel = "stylesheet";
    			link.href = url;
    			document.getElementsByTagName("head")[0].appendChild(link);
    		},
    		/**
    		 * 生成随机正整数(1-100)
    		 */
    		randomNum : function() {
    			//x上限，y下限     
    		    var x = 100;     
    		    var y = 1;     
    		    var rand = parseInt(Math.random() * (x - y + 1) + y);     

    			return rand;
    		},
            /**
             * 对日期进行格式化，
             * @param date 要格式化的日期
             * @param format 进行格式化的模式字符串
             *     支持的模式字母有：
             *     y:年,
             *     M:年中的月份(1-12),
             *     d:月份中的天(1-31),
             *     h:小时(0-23),
             *     m:分(0-59),
             *     s:秒(0-59),
             *     S:毫秒(0-999),
             *     q:季度(1-4)
             * @return String
             */
            dateFormat : function (date, format){
                date = new Date(date);
                var map = {
                    "M": date.getMonth() + 1, //月份
                    "d": date.getDate(), //日
                    "h": date.getHours(), //小时
                    "m": date.getMinutes(), //分
                    "s": date.getSeconds(), //秒
                    "q": Math.floor((date.getMonth() + 3) / 3), //季度
                    "S": date.getMilliseconds() //毫秒
                };

                format = format.replace(/([yMdhmsqS])+/g, function(all, t){
                    var v = map[t];
                    if (v !== undefined) {
                        if (all.length > 1) {
                            v = '0' + v;
                            v = v.substr(v.length - 2);
                        }
                        return v;
                    }
                    else if (t === 'y') {
                        return (date.getFullYear() + '').substr(4 - all.length);
                    }
                    return all;
                });
                return format;
            },
            //字节转换成其它类型的单位
            bytesToSize: function (bytes) {
                if (bytes === 0) return '0 B';
                var k = 1024;
                var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
                var i = Math.floor(Math.log(bytes) / Math.log(k));
                return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
            },
            //从url中根据名称获取参数
            getParameterFromByUrl: function (parameterName,url) {
                var reg = new RegExp("(^|&?)" + parameterName + "=([^&]*)(&|$)");
                var r = url.match(reg);
                if (r != null)return decodeURIComponent(r[2]);;
                return null;
            },
            //从url中根据名称获取参数
            getParameterFromUrl: function (parameterName) {
                var reg = new RegExp("(^|&)" + parameterName + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null)return decodeURIComponent(r[2]);;
                return null;
            },
            /**
             * 定时关闭消息
             * @param content  提示内容
             */
            alertTimeMsgNoCancel: function (content) {
               /* art.dialog({
                	time: 1,
                    content: content,
                    height: 60,
                    width: 300,
                    lock: true,
                    focus: true,
                    zIndex: 99999999
                });*/
            	$("body").dyArt({
            		content:content,
            		isHide:false,
            		Time:2000
            	})
            },
            /**
             * 提示框
             * callback 回调函数
             * key 提示描述
             */
            alertMsg: function (callback, content) {
                art.dialog({content: content, height: 60, width: 300, lock: true, focus: true}, function () {
                    // 先保存稿件信息
                    callback(true);
                }, function () {
                });
            },
            autoResizeImage: function (maxWidth, maxHeight, objImg) {
                var img = new Image();
                img.src = objImg.src;
                var hRatio;
                var wRatio;
                var Ratio = 1;
                var w = img.width;
                var h = img.height;
                wRatio = maxWidth / w;
                hRatio = maxHeight / h;
                if (maxWidth == 0 && maxHeight == 0) {
                    Ratio = 1;
                } else if (maxWidth == 0) {//
                    if (hRatio < 1) Ratio = hRatio;
                } else if (maxHeight == 0) {
                    if (wRatio < 1) Ratio = wRatio;
                } else if (wRatio < 1 || hRatio < 1) {
                    Ratio = (wRatio <= hRatio ? wRatio : hRatio);
                }
                if (Ratio < 1) {
                    w = w * Ratio;
                    h = h * Ratio;
                }
                objImg.height = h;
                objImg.width = w;
            },
          //显示数据加载中遮罩
            showLoading:function(select) {
                $(select).showLoading();
            },
            //隐藏数据加载中遮罩
            hideLoading:function(select) {
                $(select).hideLoading();
            },
            //弹出页面
            tipsWindowsDialog:function(title,content,width,height,drag,time,showbg,cssName){
                tipsWindown(title,content,width,height,drag,time,showbg,cssName)
            },
            /**
             * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空，则返回空字符串。</br>
             * 例如：HelloWorld->HELLO_WORLD
             * @param name 转换前的驼峰式命名的字符串
             * @return 转换后下划线大写方式命名的字符串
             */
            underScoreName : function(name) {
            	if(cmedit.global.isNotEmpty(name)){
            		var result = name.replace(/([A-Z])/g,"_$1").toLowerCase()
                    return result.toString();
            	}else{
            		return "";
            	}
                
            },

            /**
             * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空，则返回空字符串。</br>
             * 例如：HELLO_WORLD->HelloWorld
             * @param name 转换前的下划线大写方式命名的字符串
             * @return 转换后的驼峰式命名的字符串
             */
            camelName : function(name) {
            	if(cmedit.global.isNotEmpty(name)){
//            		var re=/_(\w)/g;
            		var result = name.replace(/_(\w)/g, function(all, letter){
          	          return letter.toUpperCase();
          	        })
          	        return result.toString();
            	}else{
            		return "";
            	}
            	
            },
            /**
             * 获取用户信息
             * @param dyportalServer
             * @returns
             */
            getUserInfo : function(dyportalServer,portalkey_storage){
            	var casData = null;
            	$.ajax({
                    async: false,
                    url: dyportalServer + "UserInfoController/getUserInfo",
                    data: {
                        key: portalkey_storage
                    },
                    type: 'POST',
                    dataType: 'json',
                    success : function(data){
                    	if (data.status == true || data.status == 'true') { //判断redis中用户信息是否存在
                    		casData = data.data;
                    	}
                    }
                });
            	return casData;
        	},
            ajaxRequest: function (opts) {
                // 一.设置默认参数
                var defaults = {
                    url: '',
                    type: '',
                    data: '',
                    cache: true,
                    async: false,
                    dataType: 'json',
                    success: function () {
                    },
                    error: function () {
                    }
                };

                // 二.用户参数覆盖默认参数
                for (var key in opts) {
                    defaults[key] = opts[key];
                }
                var userInfo={
                		tenantId : "dayang.com",
                		userId : "0003",
                		token : "a",
                		userName : "dayang"
                }
                window.sessionStorage.setItem("userInfo",JSON.stringify(userInfo));
                var userInfoItem = window.sessionStorage.getItem("userInfo");
                var userInfo = null;
                var userId = "";
                var tenantId = "";
                var userName = "";
                var token = "";
                if (userInfoItem != undefined && userInfoItem != null && userInfoItem != "" && userInfoItem != "undefined" && userInfoItem != "null") {
                    userInfo = JSON.parse(userInfoItem);
                    userId = userInfo.userId;
                    tenantId = userInfo.tenantId;
                    token = userInfo.token;
                    userName=userInfo.userName;
                } else {
                	cmedit.global.forceLogout("用户信息为空！");
                }
                
                var tenantId = window.localStorage.getItem("tenantId");
                var userId = window.localStorage.getItem("userId");
                var token = window.localStorage.getItem("token");
                var userName = window.localStorage.getItem("userName");
                userName = encodeURIComponent(userName);
                
//                cmedit.ManuscriptSystem.updatePortalStorageExpireTime();
                // 三.开始组装ajax
                $.ajax({
                    url: defaults.url,
                    type: defaults.type,
                    data: defaults.data,
                    async: defaults.async,
                    cache: defaults.cache,
                    dataType: defaults.dataType,
                    contentType: defaults.contentType,
                    beforeSend: function (XHR) {
                        XHR.setRequestHeader("userId", userId);
                        XHR.setRequestHeader("tenantId", tenantId);
                        XHR.setRequestHeader("token", token);
                        XHR.setRequestHeader("userName", userName);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log("错误信息" + errorThrown.toString());
                    },
                    success: defaults.success
                });
            },
        };
    })(jQuery, window, document);
//调用初始化方法
$(cmedit.global.init());